<template>
  <div>
    <!-- 查询区域 -->
    <div class="card" style="margin-bottom: 5px">
      <el-card>
        <el-input
          style="width: 200px; margin-right: 10px"
          v-model="course.name"
          placeholder="请输入课程名查询"
          prefix-icon="Search"
        />
        <el-input
          style="width: 200px; margin-right: 10px"
          v-model="course.id"
          placeholder="请输入CID查询"
          prefix-icon="Search"
        />
        <el-button type="primary" @click="load">查 询</el-button>
        <el-button type="warning" @click="reset">重 置</el-button>
      </el-card>
    </div>

    <!-- 操作按钮 -->
    <div class="card" style="margin-bottom: 5px">
      <el-button type="primary" @click="handleAdd">新 增</el-button>
      <el-button type="danger" @click="handleBatchDelete">批量删除</el-button>
    </div>

    <!-- 表格 -->
    <div class="card" style="margin-bottom: 5px">
      <el-table
        :data="course.tableData"
        border
        style="width: 100%"
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="编号" type="index" width="60" />
        <el-table-column label="cid" prop="cid" />
        <el-table-column label="课程名称" prop="cname" />
        <el-table-column label="教练ID" prop="eid" />
        <el-table-column label="开始时间" prop="stime" />
        <el-table-column label="结束时间" prop="etime" />
        <el-table-column label="人数" prop="count" />
        <el-table-column label="课时数" prop="classHours" />
        <el-table-column label="价格" prop="fullPrice" />
        <el-table-column label="操作">
          <template #default="scope">
            <div>
            <el-button
              type="primary"
              :icon="Edit"
              size="small"
              @click="handleEdit(scope.row)"
            >
              编 辑
            </el-button></div>
            <el-button
              type="danger"
              :icon="Delete"
              size="small"
              @click="handleDelete(scope.row)"
            >
              删 除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div style="margin-top: 20px; text-align: right;">
        <el-pagination
          @size-change="load"
          @current-change="load"
          v-model:current-page="course.pageNumber"
          v-model:page-size="course.pageSize"
          :page-sizes="[5, 10, 15, 20]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="course.total"
          background
        />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="course.form.cid ? '编辑课程' : '新增课程'" v-model="course.formVisible" width="600">
      <el-form :model="course.form" style="padding-right: 50px; padding-top: 20px;">
        <el-form-item label="课程名称" label-width="100px">
          <el-input v-model="course.form.cname" placeholder="请输入课程名称" />
        </el-form-item>
        <el-form-item label="教练ID" label-width="100px">
          <el-input v-model.number="course.form.eid" placeholder="请输入教练ID" />
        </el-form-item>
        <el-form-item label="开始时间" label-width="100px">
          <el-date-picker v-model="course.form.stime" type="datetime" placeholder="选择开始时间" />
        </el-form-item>
        <el-form-item label="结束时间" label-width="100px">
          <el-date-picker v-model="course.form.etime" type="datetime" placeholder="选择结束时间" />
        </el-form-item>
        <el-form-item label="人数" label-width="100px">
          <el-input-number v-model="course.form.count" :min="1" />
        </el-form-item>
        <el-form-item label="课时数" label-width="100px">
          <el-input-number v-model="course.form.class_hours" :min="1" />
        </el-form-item>
        <el-form-item label="价格" label-width="100px">
          <el-input-number v-model="course.form.full_price" :precision="2" :step="10" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="course.formVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { onMounted, reactive } from 'vue'
import request from '@/utils/request'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Edit, Delete } from '@element-plus/icons-vue'
import { useRoute } from 'vue-router'

const course = reactive({
  name: '',
  id: '',
  pageNumber: 1,
  pageSize: 10,
  total: 0,
  tableData: [],
  formVisible: false,
  form: {},
  selectedRows: [] // 用于存储用户选择的行数据
})

// 加载数据
const load = () => {
  request.get('/v1/admin/selectPage', {
    params: {
      tableName: 'course',
      name: course.name,
      id: course.id,
      pageNum: course.pageNumber,
      pageSize: course.pageSize
    }
  }).then(res => {
    console.log('响应数据:', res)
    if (res.state === 2001) {
      course.tableData = res.data.list || []
      course.total = res.data.total || 0
    } else {
      course.tableData = []
      course.total = 0
    }
  }).catch(error => {
    console.error('请求失败:', error)
    course.tableData = []
    course.total = 0
  })
}

// 重置查询条件
const reset = () => {
  course.name = ''
  course.id = ''
  load()
}

// 处理新增
const handleAdd = () => {
  course.form = {
    cname: '',
    eid: '',
    stime: null,
    etime: null,
    count: 10,
    class_hours: 10,
    full_price: 100.0
  }
  course.formVisible = true
}

// 处理编辑
const handleEdit = (row) => {
  course.form = { ...row }
  course.formVisible = true
}

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该课程吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    request.delete('/v1/admin/delete', {
      data: {
        tableName: 'course',
        id: row.cid
      }
    }).then(res => {
      if (res.state === 2001) {
        ElMessage({ message: '删除成功', type: 'success' })
        load()
      } else {
        ElMessage({ message: '删除失败', type: 'error' })
      }
    }).catch(error => {
      console.error('请求失败:', error)
      ElMessage({ message: '请求失败，请检查网络或服务器', type: 'error' })
    })
  }).catch(() => {
    // 用户取消删除
  })
}

// 处理批量删除
const handleBatchDelete = () => {
  if (course.selectedRows.length === 0) {
    ElMessage({ message: '请选择要删除的课程', type: 'warning' })
    return
  }

  ElMessageBox.confirm('确定要删除这些课程吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const ids = course.selectedRows.map(row => row.cid) // 获取所有选中行的 cid
    request.delete('/v1/admin/batchDelete', {
      data: {
        tableName: 'course',
        ids: ids // 传递要删除的 cid 列表
      }
    }).then(res => {
      if (res.state === 2001) {
        ElMessage({ message: '批量删除成功', type: 'success' })
        load()
      } else {
        ElMessage({ message: '批量删除失败', type: 'error' })
      }
    }).catch(error => {
      console.error('请求失败:', error)
      ElMessage({ message: '请求失败，请检查网络或服务器', type: 'error' })
    })
  }).catch(() => {
    // 用户取消删除
  })
}

// 处理用户选择的行数据
const handleSelectionChange = (rows) => {
  course.selectedRows = rows
}

// 保存新增或编辑
const save = () => {
  const method = course.form.cid ? 'put' : 'post'
  const url = course.form.cid ? '/v1/admin/update' : '/v1/admin/add'

  // 格式化日期时间
  const formattedData = {
    ...course.form,
    stime: course.form.stime ? new Date(course.form.stime).toISOString().slice(0, 19).replace('T', ' ') : null,
    etime: course.form.etime ? new Date(course.form.etime).toISOString().slice(0, 19).replace('T', ' ') : null
  }

  request[method](url, {
    tableName: 'course',
    data: formattedData
  }).then(res => {
    if (res.state === 2001) {
      ElMessage({
        message: course.form.cid ? '编辑成功' : '新增成功',
        type: 'success'
      })
      course.formVisible = false
      load()
    } else {
      ElMessage({
        message: course.form.cid ? '编辑失败' : '新增失败',
        type: 'error'
      })
    }
  }).catch(error => {
    console.error('请求失败:', error)
    ElMessage({ message: '请求失败，请检查网络或服务器', type: 'error' })
  })
}


// 初始化加载数据
load()

const route = useRoute()

onMounted(() => {
  const cid = route.params.cid
  if (cid) {
    course.id = cid
    load()
  }
})
</script>

<style scoped>
.card {
  margin-bottom: 10px;
}
</style>
